const express = require('express'),
  router = express.Router(),
  util = require("../util/util"),
  price = require("../model/price"),
  book = require("../model/book"),
    chapter = require("../model/chapter");

let reObj = util.reObj;


/**
 * @function 添加校区信息
 * @author Eric
 * @date 2018-08-01
 * @param name,code,addr,area,status
 */
router.post('/add', (req, res) => {
    let name=req.body.name;
    let queryparam = {
        bookid:req.body.bookid,
        name:name
    }
    let bookparams={bookid:req.body.bookid}
    chapter.findOrCreate({
        where: queryparam,
        defaults: req.body
    }).then(record => {      
        if (record[1]) {
          chapter.update({sortid:record[0].id}, {where: {id:record[0].id}})
          chapter.findAndCountAll({            
            limit:  1000,
            offset: parseInt(999 * (1 - 1)) || 0,
            where: bookparams
          }).then(records => {
            let updateData={
              id:""
          }
            if(records.count===1)
            {
              updateData.id=record[0].id
              updateData.sortid=record[0].id
              updateData.next="end"
              chapter.update(updateData, {where: {id:record[0].id}})  
              book.update({nextid:record[0].id}, {where: {id:req.body.bookid}})  
                          
            }
            else
            {              
              for(i=0;i<records.rows.length;i++)
    {
        if(i>0&&i<records.rows.length-1)
        {
            console.log("A")
            console.log("prev:"+records.rows[i-1].id)
            console.log("id:"+records.rows[i].id)
            console.log("next:"+records.rows[i+1].id)
            updateData.prev=records.rows[i-1].sortid
            updateData.id=records.rows[i].id
            updateData.sortid=records.rows[i].id
            updateData.next=records.rows[i+1].sortid
            chapter.update(updateData, {where: {id:updateData.id}})  
            /* book.update({nextid:record[0].id}, {where: {id:req.body.bookid}})  
            await superagent.post(updateChapterUrl).send(updateData) */
        }
        else if(i===records.rows.length-1)
        {
            console.log("B")
            console.log("prev:"+records.rows[i-1].id)
            console.log("id:"+records.rows[i].id)
            console.log("next:end")
            updateData.prev=records.rows[i-1].sortid
            updateData.id=records.rows[i].id
            updateData.sortid=records.rows[i].id
            updateData.next="end"
            chapter.update(updateData, {where: {id:updateData.id}})  
            //await superagent.post(updateChapterUrl).send(updateData)
        }
        else
        {
            console.log("C")
            console.log("id:"+records.rows[i].id)
            console.log("next:"+records.rows[i+1].id)
            updateData.prev=""
            updateData.id=records.rows[i].id
            updateData.sortid=records.rows[i].id
            updateData.next=records.rows[i+1].sortid
            chapter.update(updateData, {where: {id:updateData.id}}) 
            book.update({nextid:records.rows[i].id}, {where: {id:req.body.bookid}})  
            //await superagent.post(updateChapterUrl).send(updateData)
        }
      }
            }                                    
          })
            res.send(reObj(0, '添加成功', record[0]))
        } else {
            res.send(reObj(-1, '记录已存在'))
        }
    }).catch(err => {
      console.log("err:"+(err))
        res.send(reObj(-1, '添加失败', err))
    });

})

/**
 * @function 编辑校区信息
 * @author Eric
 * @date 2018-08-01
 * @param id,name,code,addr,area,status
 */
router.post('/update', (req, res) => {
  let id = req.body.id
  let params = {
    id: id
  }

    chapter.update(req.body, {where: params}).then(record => {
        if (record[0] > 0) {
            res.send(reObj(0, '修改成功', record[0]))
        } else {
            res.send(reObj(-1, '无效id', []))
        }
    }).catch(err => {
        res.send(reObj(-1, '修改会议信息失败', err))
    });

})

/**
 * @function 删除对应的会议数据
 * @author Eric
 * @date 2018-07-31
 * @param id
 */
router.post('/del', (req, res) => {
  let params = {
    id: req.body.id
  }

  chapter.destroy({where: params}).then(record => {
    if (record > 0) {
      res.send(reObj(0, '删除成功', record))
    } else {
      res.send(reObj(-1, '删除失败或此记录不存在', record))
    }
  }).catch(err => {
    res.send(reObj(-1, '删除会议失败', err))
  });
})

/**
 * @function 获取单个信息
 * @author Eric
 * @date 2018-08-01
 * @param meetingid
 */
router.post('/findone', async (req, res) => {
  let params = {}
  let id = req.body.id
  try {
    if (id) {
      let record=await chapter.findOne({where: {sortid:id}})
      let chapterRecord=await price.findOne({where:{chapterid:id}})      
    if (record) {
      let newRecord=JSON.parse(JSON.stringify(record))
      if(chapterRecord)
      {
        newRecord.price=chapterRecord.price
      }
      let priceRecord=await price.findOne({where:{bookid:newRecord.bookid}})      
      if(priceRecord&&parseInt(priceRecord.chapterid)<parseInt(id))
      {
        newRecord.price=priceRecord.price        
      }
      
      res.send(reObj(0, '获取信息成功', newRecord))
    } else {
      res.send(reObj(-1, '获取信息失败或此记录不存在', {}))
    }
    }
    else
    {
      res.send(reObj(-1, 'id不能为空', []))
    }
    
  } catch (error) {    
    res.send(reObj(-1, '获取信息失败', error))
  }
  /* if (id) {
    params.id = id;

    chapter.findOne({where: params}).then(record => {
      if (record) {
        res.send(reObj(0, '获取信息成功', record))
      } else {
        res.send(reObj(-1, '获取信息失败或此记录不存在', {}))
      }
    }).catch(err => {
      res.send(reObj(-1, '获取信息失败', err))
    });
  } else {
    res.send(reObj(-1, 'id不能为空', []))
  } */
})


router.post('/move', async (req, res) => {
  let upid = req.body.upid
  let downid = req.body.downid
  let upparams = {
    id: upid
  }
  let downparams = {
    id: downid
  }
  try {
    let upRecord= await chapter.findOne({where: upparams})
    let downRecord= await chapter.findOne({where: downparams})
    await chapter.update({sortid:upRecord.sortid}, {where: {id:downRecord.id}})
    await chapter.update({sortid:downRecord.sortid}, {where: {id:upRecord.id}}) 
    chapter.findAndCountAll({   
      order: "sortid ASC",         
      limit:  1000,
      offset: parseInt(999 * (1 - 1)) || 0,
      where: {bookid:upRecord.bookid}
    }).then(records => {
      let updateData={}
      if(records.count===1)
      {
        
        book.update({nextid:record[0].sortid}, {where: {id:upRecord.bookid}})  
                    
      }
      else
      {              
        for(i=0;i<records.rows.length;i++)
{
  if(i>0&&i<records.rows.length-1)
  {
      console.log("A")
      console.log("prev:"+records.rows[i-1].sortid)
      console.log("id:"+records.rows[i].sortid)
      console.log("next:"+records.rows[i+1].sortid)
      updateData.prev=records.rows[i-1].sortid
    //  updateData.id=records.rows[i].sortid
      updateData.next=records.rows[i+1].sortid
      
      chapter.update(updateData, {where: {sortid:records.rows[i].sortid}})  
      /* book.update({nextid:record[0].id}, {where: {id:req.body.bookid}})  
      await superagent.post(updateChapterUrl).send(updateData) */
  }
  else if(i===records.rows.length-1)
  {
      console.log("B")
      console.log("prev:"+records.rows[i-1].sortid)
      console.log("id:"+records.rows[i].sortid)
      console.log("next:end")
      updateData.prev=records.rows[i-1].sortid
     // updateData.id=records.rows[i].sortid
      updateData.next="end"
      chapter.update(updateData, {where: {sortid:records.rows[i].sortid}})  
      //await superagent.post(updateChapterUrl).send(updateData)
  }
  else
  {
      console.log("C")
      console.log("id:"+records.rows[i].sortid)
      console.log("next:"+records.rows[i+1].sortid)
      //updateData.id=records.rows[i].sortid
      updateData.prev=""
      updateData.next=records.rows[i+1].sortid
      chapter.update(updateData, {where: {sortid:records.rows[i].sortid}})  
      book.update({nextid:records.rows[i].sortid}, {where: {id:upRecord.bookid}})        
      //await superagent.post(updateChapterUrl).send(updateData)
  }
}
      }                                    
    })
    
     
  res.send(reObj(0, '更新成功', upRecord))
  } catch (error) {
    res.send(reObj(-1, '更新失败', error))
  }
})

/**
 * @function 获取所有数据(支持分页，条件过滤)
 * @author Eric
 * @date 2018-07-31
 * @param page,pagerow,meetingname,meetingtype
 */
router.post('/findall', (req, res) => {
 /* let meetingname = req.body.meetingname || ''
  let meetingtype = req.body.meetingtype || ''*/
  let params = req.body
  let pagerow = parseInt(req.body.pagerow)
  let page = parseInt(req.body.page)
  if(pagerow){
    delete params.pagerow;
  }
  if(page){
    delete params.page;
  }
  //对页码进行容错
  if (pagerow > 999) {
    pagerow = 999
  }
  if (page == 0) {
    page = 1
  }


  //筛选条件
/*  if (meetingname) {
    params.meetingname = {'$like': '%' + meetingname + '%'}
  }
  if (meetingtype) {
    params.meetingtype = meetingtype
  }*/

  let sort="sortid ASC"
    if(req.body.sort==="DESC")
    {
      sort="sortid DESC"
    }
    else
    {
      sort="sortid ASC"
    }
    delete params["sort"]    
  chapter.findAndCountAll({
    order: sort,
    limit: pagerow || 1000,
    offset: parseInt(pagerow * (page - 1)) || 0,
    where: params
  }).then(record => {
    if(record.count>0){
      res.send(reObj(0, '获取数据成功', record.rows, record.count))
    }
    else
    {
      res.send(reObj(0, '没有符合条件的记录', record.rows, record.count))
    }
    
  }).catch(err => {
    res.send(reObj(-1, '获取数据失败', err))
  });
})


module.exports = router;
